package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.adapter.ListViewAdapter;
import com.ciwong.epaper.modules.me.bean.Duiba;
import com.ciwong.epaper.modules.me.bean.MenuOptionBean;
import com.ciwong.epaper.modules.me.bean.UserBg;
import com.ciwong.epaper.modules.me.bean.UserInforDetailBean;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.epaper.widget.DampScrollView;
import com.ciwong.epaper.widget.NewBottomMenuDialog;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.NoScrollListView;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.OnItemClickListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by RES-KUNZHU on 2015/7/24.
 */
public class MeFragment extends BaseFragment {

    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;
    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;
    /**
     * 跳转码，拍照裁剪图片
     */
    public static final int REQUEST_CODE_CROP_CAMERA = 0x0000013;
    /**
     * 跳转码，相册裁剪图片
     */
    public static final int REQUEST_CODE_CROP_ALBUM = 0x0000014;
    /**
     * 去修改个人信息
     */
    public static final int REQUEST_CODE_TO_MODIFY_USER_INFO = 0x0000015;
    /**
     * 我的服务列表
     */
    public static final int REQUEST_CODE_TO_MY_SERVICES = 0x0000016;
    private final String TAG = "MeFragment";
    private Activity mActivity;
    private View view;
    private EApplication application;
    private UserInfoBase userInfo;
    private SchoolDetail schoolDetail;
    //测试视频讲解入口
    private List<SchoolDetail> mSchoolDetailList;
    public DampScrollView dampScrollView;
    private NoScrollListView listView;
    private ListViewAdapter adapter;
    private View content_view;
    private SimpleDraweeView img_user_avatar;
    private SimpleDraweeView img_personal_page_top;
    private TextView user_name_account;
    private TextView tx_school_class;
    private RelativeLayout handle_top;
    private int width, height;
    private CWDialog getSDcardPermissDialog;
    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    public static final String IS_USE_EYE_GUARD_MODE = "IS_USE_EYE_GUARD_MODE_";
    private ViewOnClickListener mViewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.img_user_avatar || id == R.id.user_name_account) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(getActivity());
                    newLoginDialog.showLoginDialog();
                } else {
                    MeJumpManager.jumpToMyInfo(MeFragment.this, R.string.go_back, REQUEST_CODE_TO_MODIFY_USER_INFO);
                }

            } else if (id == R.id.img_personal_page_top) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(getActivity());
                    newLoginDialog.showLoginDialog();

                } else {
                    bottomMenuDialog.show();
                }
            } else if (id == R.id.iv_setting_assess) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_ASSESS + ((MainActivity) mActivity).getUserInfoBase().getUserId(), v.isSelected());

            } else if (id == R.id.iv_setting_listen_speak) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + ((MainActivity) mActivity).getUserInfoBase().getUserId(), v.isSelected());
            }
        }
    };

    private AdapterView.OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void avertRepeatOnClick(AdapterView<?> adapterView, View view, int i, long l) {

            switch (i) {
                case 0:
                    //跳转至个人信息
                    MeJumpManager.jumpToMyInfo(MeFragment.this, R.string.go_back, REQUEST_CODE_TO_MODIFY_USER_INFO);
                    break;
                case 1:
                    //联系我们
                    MeJumpManager.jumpToKeFu(mActivity, R.string.go_back);
                    break;
                case 2:
                    //跳到投诉
                    MeJumpManager.jumpToIssueRespActivity(R.string.go_back, getActivity());
                    break;
                case 3:
                    //注销账号
                    MeJumpManager.jumpWrittenOffActivity(R.string.go_back, getActivity(), getString(R.string.written_off_url), getString(R.string.written_off));
                    break;
                case 4:
                    //关于我们
                    MeJumpManager.jumpToAboutUs(mActivity, R.string.go_back);
                    break;
                case 5:
                    //撤销同意声明
                    MeJumpManager.jumpToAreementCancel(getActivity(), R.string.go_back,
                            getString(R.string.agreement_cancel_url), "撤销同意声明");

            }
        }
    };


    private Object userInfor;

    public MeFragment() {
        super();
    }

    private CWDialog cWDialog;

    private void showConfirmDialog(Context context) {
        if (context != null) {
            String msgTips = getString(R.string.dialog_hu_yan_tips);
            showConfirmDialog(context, msgTips);
        }

    }

    private void showConfirmDialog(Context context, CharSequence message) {
        if (cWDialog != null && cWDialog.isShowing()) {
            cWDialog.dismiss();
        }
        cWDialog = new CWDialog(context);
        cWDialog.setMessagWidePadding(message).setPositiveButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWDialog.dismiss();
            }
        }).show();

        cWDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cWDialog.dismiss();
            }
        });
    }

    /**
     * 创建一个实例
     *
     * @return 返回一个实例
     */
    public static MeFragment newInstance() {
        MeFragment meFragment = new MeFragment();
        return meFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_me, null);
        findView(view);
        init();
        return view;
    }

    private void findView(View view) {
        user_name_account = view.findViewById(R.id.user_name_account);
        tx_school_class = view.findViewById(R.id.tx_school_class);
        dampScrollView = view.findViewById(R.id.dampScrollView);
        listView = view.findViewById(R.id.noscroll_listview);
        content_view = view.findViewById(R.id.content_view);
        dampScrollView.setbackGroundView(content_view);
        img_user_avatar = view.findViewById(R.id.img_user_avatar);
        img_personal_page_top = view.findViewById(R.id.img_personal_page_top);

        listView.setFocusable(false);
        adapter = new ListViewAdapter(getActivity(), getDatas());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(onItemClickListener);
        user_name_account.setOnClickListener(mViewOnClickListener);
        handle_top = view.findViewById(R.id.handle_top);

    }


    public List<String> getDatas() {
        List<String> datas = new ArrayList<String>();
        datas.add("个人信息");
        datas.add("联系我们");
        datas.add("投诉");
        datas.add("注销账号");
        datas.add("关于习习教师");
        datas.add("撤销同意声明");
        return datas;
    }

    private void init() {
        tempFile = ESystem.getPicturesCacheDir(getActivity(), ESystem.getCacheFileName("meinfo", "jpg"));
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels - DeviceUtils.dip2px(92);

        img_user_avatar.setOnClickListener(mViewOnClickListener);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) handle_top.getLayoutParams();

        params.width = width;
        params.height = width;
        handle_top.setLayoutParams(params);

        RelativeLayout.LayoutParams paramsImg = (RelativeLayout.LayoutParams) img_personal_page_top.getLayoutParams();
        paramsImg.width = width;
        paramsImg.height = width;

        img_personal_page_top.setLayoutParams(paramsImg);

        img_personal_page_top.setOnClickListener(mViewOnClickListener);
        application = (EApplication) mActivity.getApplication();
        setUserInfo();
        setBottomMenuDialog();
        ALiYunManager.getInstance().registerListener(listener);
    }

    /**
     * //     * 设置用户信息
     * //
     */
    public void setUserInfo() {

        UserBg userBg = null;
        try {
            userBg = (UserBg) CWSys.getSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_USER_BG + SerializableManager.getInstance().getUserId(true));
            if (null != userBg) {
                Uri uri = Uri.parse(userBg.getBackGround());
                img_personal_page_top.setImageURI(uri);
            } else {
                updateOrGetUserBg(null, true);
            }
            updateOrGetUserBg(null, true);
        } catch (IOException e) {
            e.printStackTrace();
            updateOrGetUserBg(null, true);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            updateOrGetUserBg(null, true);
        }
        try {
            userInfo = application.getUserInfoBase();
            if (null != userInfo) {
                String avatar = userInfo.getAvatar();
                if (!TextUtils.isEmpty(avatar)) {
                    Uri uri = Uri.parse(avatar);
                    img_user_avatar.setImageURI(uri);
                } else {
                    ViewUtil.setLocalDefaultImg(img_user_avatar, R.mipmap.head);
                }
                user_name_account.setText(userInfo.getRealName() + "  ");
            }

            schoolDetail = application.getSchoolDetail();
            if (schoolDetail == null) {
                getSchoolByServer();
            } else {
                tx_school_class.setText(schoolDetail.getSchoolName());
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }
    }

    /**
     * 获取学校信息
     */
    private void getSchoolByServer() {
        if (null == EApplication.getInstance().getUserInfoBase()) {
            CWLog.d(TAG, "#######null == EApplication.getInstance().getUserInfoBase()##########");
            return;
        }
        schoolDetail = EApplication.getInstance().getMySchool();
        if (null == schoolDetail) {
            return;
        } else {
            tx_school_class.setText(schoolDetail.getSchoolName());
        }
        try {
            //刷新数据库的schoolId
            if (EApplication.PLATFORM_ENV == EApplication.PLATFORM_PAD && schoolDetail != null) {
                int schoolId = schoolDetail.getSchoolId();
                LoginToken loginToken = LoginToken.queryTokenAndUserInfo(getActivity().getContentResolver());
                if (null != loginToken) {
                    if (loginToken.getSchoolId() != schoolId) {
                        loginToken.setSchoolId(schoolId);
                        LoginToken.updateSchoolId(getActivity().getContentResolver(), loginToken);
                    }

                }
            }
        } catch (Exception e) {

        }
    }

    private void getSchoolByLocal() {
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_ALL_SCHOOL, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                mSchoolDetailList = (List<SchoolDetail>) data;
                if (!mSchoolDetailList.isEmpty()) {
                    schoolDetail = mSchoolDetailList.get(0);
                    application.setSchoolDetail(schoolDetail);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInforDetail();
    }

    public void getDuibaLoginurl() {
        try {
            MeDao.getInstance().getDuibaLoginurl(new BaseCallBack() {

                @Override
                public void success(Object data) {
                    super.success(data);
                    if (null != data) {
                        Duiba duiba = (Duiba) data;
                        String url = duiba.getDuiBaUrl();
                        if (url != null) {
                            MeJumpManager.jumpToDuiBaActivity(getActivity(), R.string.go_back, url);
                        }
                    }


                }

                @Override
                public void failed(int errorCode, Object data) {

                }

                @Override
                public void failed(Object data) {

                }
            }, application.getUserInfoBase().getUserId() + "");
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


/*    public void getUserInforDetail() {
        MeDao.getInstance().getUserInforDetail(new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                CWLog.d(TAG, "data:" + data + errorCode);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "data:" + data);
            }

            @Override
            public void success(Object data) {
                super.success(data);
                if (data == null)
                    return;
                UserInforDetailBean userInforAndPointRankBean = (UserInforDetailBean) data;
                refrashPersonInfor(userInforAndPointRankBean);
                CWLog.d(TAG, "data:" + data);
            }
        });
    }*/

    public void getUserInforDetail() {
        MeDao.getInstance().getUserInforDetail(new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "data:" + data + errorCode);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "data:" + data);
            }

            @Override
            public void success(Object data) {
                super.success(data);
                if (data == null)
                    return;
                UserInforDetailBean userInforAndPointRankBean = (UserInforDetailBean) data;
                refrashPersonInfor(userInforAndPointRankBean);
                CWLog.d(TAG, "data:" + data);
            }
        });
    }

    /**
     * 刷新个人信息
     *
     * @param userInforAndPointRankBean
     */
    private void refrashPersonInfor(UserInforDetailBean userInforAndPointRankBean) {
        if (!TextUtils.isEmpty(userInforAndPointRankBean.getAvatar())) {
            Uri uri = Uri.parse(userInforAndPointRankBean.getAvatar());
            img_user_avatar.setImageURI(uri);
        } else {
            ViewUtil.setLocalDefaultImg(img_user_avatar, R.mipmap.head);
        }
        user_name_account.setText(userInforAndPointRankBean.getRealName() + "  ");
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ALiYunManager.getInstance().unRegisterListener(listener);
    }


    private File cutImgFile;
    private File cutImgFileTemp;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri outPuturi;
            switch (requestCode) {
                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(getActivity(), tempFile);
//                    if (Build.VERSION.SDK_INT >= 30) {
                    cutImgFile = FileUtil.uriToFileApiQ(photoUri, getActivity());
//                    } else {
//                        cutImgFile = new File(ESystem.getUploadImgPath(), ESystem.getCacheFileName("meinfo", "jpg"));
//                    }
                    showGetPermissDialog();

                    break;
                case REQUEST_CODE_ALBUM:
                    if (data != null) {
                        photoUri = data.getData();
                        if (photoUri != null) {
//                            if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFile = FileUtil.uriToFileApiQ(photoUri, getActivity());
//                            } else {
//                                cutImgFile = new File(ESystem.getUploadImgPath(), ESystem.getCacheFileName("meinfo", "jpg"));
//                            }
                            showGetPermissDialog();
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_ALBUM:
                case REQUEST_CODE_CROP_CAMERA:
                    if (null != cutImgFileTemp) {
                        CWLog.i("byou", "cutImgFile.getPath()=" + cutImgFile.getPath());
                        if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.getCropFile(getContext(), com.ciwong.mobilelib.utils.FileUtil.uri);
                        }
                        uploadAvatar(cutImgFileTemp.getPath());
                    }
                    break;
                case REQUEST_CODE_TO_MODIFY_USER_INFO:
                    if (data != null) {
                        int type = data.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
                        switch (type) {
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_AVATAR:// 修改头像成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_NAME:// 修改姓名成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_SCHOOL:// 修改学校成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_CLASS:// 修改班级成功后回调
                                setUserInfo();
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case CODE_REQUEST_ALBUM_PERMISSION:
                    if (XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
                    }
                    break;
                case CODE_REQUEST_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.CAMERA)) {
                        tempFile = ESystem.getPicturesCacheDir(getActivity(), ESystem.getCacheFileName("meinfo", "jpg"));
                        BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
                    }
                    break;
            }
        }

    }

    private File tempFile;

    private NewBottomMenuDialog bottomMenuDialog;

    private Uri photoUri;
    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;
    private final int CODE_REQUEST_SAOYISAO_CAMERA_PERMISSION = 9902;
    private AdapterView.OnItemClickListener bgOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {

                case 0:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                case 1:// 拍照
                    showgetCameraPermissDialog();
                    break;
                default:
                    break;
            }
            if (null != bottomMenuDialog && bottomMenuDialog.isShowing()) {
                bottomMenuDialog.dismiss();
            }
        }
    };

    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(getActivity());
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(getActivity());
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.READ_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读取相册权限，无法正常使用相册。");
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
        }
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            noteMap.put(Manifest.permission.CAMERA, "相机权限");
            permissionList.add(Manifest.permission.CAMERA);
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                tempFile = ESystem.getPicturesCacheDir(getActivity(), ESystem.getCacheFileName("meinfo", "jpg"));
                                BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到使用相机权限，无法正常使用照相机。");
                            }
                        }
                    });
        } else {
            tempFile = ESystem.getPicturesCacheDir(getActivity(), ESystem.getCacheFileName("meinfo", "jpg"));
            BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
        }
    }

    private CWDialog prmisDialog;

    /**
     * 提醒窗口
     */
    private void showConfirmCommitDialog(final Activity context, final String tips) {
        if (prmisDialog == null) {
            prmisDialog = new CWDialog(context);
        }
        prmisDialog.setMessage(tips);
        prmisDialog.setNegativeButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        prmisDialog.dismiss();
                    }
                }).show();
    }

    private void setBottomMenuDialog() {
        bottomMenuDialog = new NewBottomMenuDialog(getActivity());
        bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_photo, "从相册中选择"));
        bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_caram, "拍照"));
        bottomMenuDialog.setOnItemClickListener(bgOnItemClickListener);
    }

    /**
     * 上传头像
     */
    private void uploadAvatar(final String localPath) {
        File file = new File(localPath);
        if (file.exists()) {
            showCricleProgress();
            ALiYunManager.getInstance().add(localPath, localPath);
        } else {
            showToastError("文件不存在");
        }
    }

    private void updateOrGetUserBg(final String url, final boolean isGet) {
        if (EApplication.getInstance() == null || EApplication.getInstance().getUserInfoBase() == null || EApplication.getInstance().getUserInfoBase().getUserId() <= 0)
            return;
        MeDao.getInstance().updateUserBgInfo(url, isGet, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(Object data) {
                if (data != null) {
                    // 修改我的页面背景成功
                    UserBg userBg = (UserBg) data;
                    Uri uri = null;
                    if (isGet) {
                        uri = Uri.parse(((UserBg) data).getBackGround());
                    } else if (!TextUtils.isEmpty(url)) {
                        uri = Uri.parse(url);
                        showToastSuccess(R.string.modify_user_bg_success);

                    }
                    if (null != uri)
                        img_personal_page_top.setImageURI(uri);

                    if (null != userBg) {
                        try {
                            CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_USER_BG + SerializableManager.getInstance().getUserId(true), userBg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                hideCricleProgress();
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (errorCode == 90002) {
                    showToastError(errorCode, data);
                } else if (!isGet) {
                    showToastError(R.string.modify_avatar_fail);
                }

            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                /*if (!isGet) {
                    showToastError(R.string.modify_avatar_fail);
                }*/
            }
        });
    }

    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(getActivity());
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_photo_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                Uri outPuturi = Uri.fromFile(cutImgFile);
                                Uri imgUri = FileProvider7.getUriForFile(getContext(), cutImgFile);
                                if (Build.VERSION.SDK_INT >= 30) {
                                    cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getContext(), true);
                                    //设置裁剪的图片地址Uri
                                    outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                                } else {
//                                    cutImgFileTemp = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(), System.currentTimeMillis() + ".png");
                                    cutImgFileTemp = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
                                }
                                BaseJumpManager.jumpToSysCropPhoto(getActivity(), photoUri, outPuturi, cutImgFileTemp,
                                        REQUEST_CODE_CROP_CAMERA, true, 200, 200);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            Uri outPuturi = Uri.fromFile(cutImgFile);
            Uri imgUri = FileProvider7.getUriForFile(getContext(), cutImgFile);
            if (Build.VERSION.SDK_INT >= 30) {
                cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getContext(), true);
                //设置裁剪的图片地址Uri
                outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
            } else {
                cutImgFileTemp = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
            }
            BaseJumpManager.jumpToSysCropPhoto(getActivity(), photoUri, outPuturi, cutImgFileTemp,
                    REQUEST_CODE_CROP_CAMERA, true, 200, 200);
        }
        return true;
    }

    private ALiYunManager.ALiYunListener listener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            if (null != cutImgFileTemp && cutImgFileTemp.getPath().equals(tag)) {
                FileUtils.delete(String.valueOf(tag));
                //            hideCricleProgress();
                updateOrGetUserBg(url, false);
            }
        }


        @Override
        public void onFailure(Object tag, int errorCode) {
            hideCricleProgress();

            if (null != cutImgFileTemp && cutImgFileTemp.getPath().equals(tag)) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToastError(R.string.upload_img_fail);
                    }
                });
            }
        }
    };

}
